<?php

/**
 * terapiavital actions.
 *
 * @package    sispatr
 * @subpackage terapiavital
 * @author     Foxsis
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class terapiavitalActions extends sfActionsFoxsis
{
	public function preExecute()
	{
		$this->sistema = Doctrine::getTable('Sistema')->find(1);	
	}
	
	public function executeIndex(sfWebRequest $request) { }
	
	public function executeServico(sfWebRequest $request)
	{
		$this->getResponse()->setTitle('TerapiaVital' . ' | Serviços');
	}
	
	public function executeMarketing(sfWebRequest $request)
	{
		$this->getResponse()->setTitle('TerapiaVital' . ' | Marketing');
	}
	
	public function executeInstitucional(sfWebRequest $request)
	{
		$this->getResponse()->setTitle('TerapiaVital' . ' | Institucional');
	}
	
	public function executePublico(sfWebRequest $request)
	{
		$this->getResponse()->setTitle('TerapiaVital' . ' | Para o público');
	}
	
	public function executeContato(sfWebRequest $request)
	{
		$this->getResponse()->setTitle('TerapiaVital' . ' | Fale Conosco');
	}
	
	public function executeArtigoDetalhes(sfWebRequest $request)
	{
		try {
			$this->item = $this->getRoute()->getObject();
			
			$this->getResponse()->setTitle('TerapiaVital' . ' | ' . $this->item->getNmItem());
			
		} catch(Exception $e){
			$this->getUser()->setFlash(
				'alert',
				'Não foi possível carregar o artigo, por favor tente novamente.');
			$this->redirect('@homepage');
		}
	}
	
	public function executeContatoEnviar(sfWebRequest $request)
	{
		if($this->hasRequestParameter('commit'))
		{
			$formData = new FormData($request->getParameter('faleconosco'));
			$formData->setCulture($this->getUser()->getCulture());

			$this->enviarMensagemFaleConosco($formData);

			$this->getUser()->setFlash(
				'mensagem',
				'Sua Mensagem foi enviada com sucesso, breve retornaremos o contato.');
			
			$this->redirect('@fale-conosco');
		}
	}
	
	public function handleErrorContatoEnviar()
	{
		$this->forward($this->getModuleName(), 'contato');
	}
	
	public function enviarMensagemFaleConosco($dados)
	{
		$this->setTemplate('emailFaleConosco');
		$this->dados = $dados;

		// class initialization
	    $mail = new sfMail();
	    $mail->setCharset('iso-8859-1');

	    // definition of the required parameters
	    $mail->setSender($dados->get('email'), $dados->get('nome'));
	    $mail->setFrom($dados->get('email'), $dados->get('nome'));
	    $mail->addReplyTo($dados->get('email'));
	    $mail->addAddress(sfConfig::get('app_email_sistema'));

	    $mail->setSubject('Formulário Fale Conosco ' . date('d/m/Y H:i:s'));
	    $mail->setContentType('text/html');

	    $html = utf8_decode(Util::getHtmlContent($this));

	    $mail->setBody($html);
   	 	$mail->send();
	}
	
	public function executePesquisar(sfWebRequest $request)
	{
		$pesquisa = $request->getParameter('q');
		
		$paginaAtual = $this->_setActualPage();
		$this->filter = $this->_getFilter();
		
		$listQuery = ItemTable::pesquisar($pesquisa);
		
		$this->getContext()->getConfiguration()->loadHelpers('Url');
		$this->pager_layout = new Foxsis_Pager_Layout(
			$pager = new Doctrine_Pager(
				$listQuery,
				$paginaAtual,
				NUM_LIST_ITENS
			),
			new Doctrine_Pager_Range_Sliding(array('chunk' => MAX_PAGER_LINKS)),
			url_for('@pesquisar?q=' . $pesquisa)
		);
		
		$this->itens = $this->pager_layout->execute();
		$this->setTemplate('pesquisar');
	}
	
	public function executePesquisarTag(sfWebRequest $request)
	{
		$this->tag = $request->getParameter('tag');
		
		$paginaAtual = $this->_setActualPage();
		$this->filter = $this->_getFilter();
		
		$listQuery = ItemTable::pesquisar($this->tag, true);
		
		$this->getContext()->getConfiguration()->loadHelpers('Url');
		$this->pager_layout = new Foxsis_Pager_Layout(
			$pager = new Doctrine_Pager(
				$listQuery,
				$paginaAtual,
				NUM_LIST_ITENS
			),
			new Doctrine_Pager_Range_Sliding(array('chunk' => MAX_PAGER_LINKS)),
			url_for('@tag?tag=' . $this->tag)
		);
		
		$this->itens = $this->pager_layout->execute();
		$this->setTemplate('pesquisar');
	}
	
	public function executeArtigos(sfWebRequest $request)
	{
		$paginaAtual = $this->_setActualPage();
		$this->filter = $this->_getFilter();
		
		$listQuery = ItemTable::consultarArtigoNoticia($this->filter, 'i.created_at DESC');
		
		$this->getContext()->getConfiguration()->loadHelpers('Url');
		$this->pager_layout = new Foxsis_Pager_Layout(
			$pager = new Doctrine_Pager(
				$listQuery,
				$paginaAtual,
				NUM_LIST_ITENS
			),
			new Doctrine_Pager_Range_Sliding(array('chunk' => MAX_PAGER_LINKS)),
			url_for('@artigos')
		);
		
		$this->itens = $this->pager_layout->execute();

		$this->getResponse()->setTitle('TerapiaVital' . ' | Artigos');
	}
	
	public function executeEventos(sfWebRequest $request)
	{
		$paginaAtual = $this->_setActualPage();
		$this->filter = $this->_getFilter();
		
		$listQuery = EventoTable::consultar($this->filter, 'e.created_at DESC');
		
		$this->getContext()->getConfiguration()->loadHelpers('Url');
		$this->pager_layout = new Foxsis_Pager_Layout(
			$pager = new Doctrine_Pager(
				$listQuery,
				$paginaAtual,
				NUM_LIST_ITENS
			),
			new Doctrine_Pager_Range_Sliding(array('chunk' => MAX_PAGER_LINKS)),
			url_for('@eventos')
		);
		
		$this->itens = $this->pager_layout->execute();		
		
		$this->getResponse()->setTitle('TerapiaVital' . ' | Eventos');
	}
	
	public function executeEventoDetalhes(sfWebRequest $request)
	{
		try {
			$this->evento = $this->getRoute()->getObject();
			
			$this->getResponse()->setTitle('TerapiaVital' . ' | Evento - ' . $this->evento->getNmEvento());
		} catch(Exception $e){
			$this->getUser()->setFlash(
				'alert',
				'Não foi possível carregar o Evento, por favor tente novamente.');
			$this->redirect('@eventos');
		}
	}
	
	public function executeCarregarEventoData(sfWebRequest $request)
	{
		sfLoader::loadHelpers(array('Tag', 'Url'));
		$data = $request->getParameter('data');
		$data = substr($data, 0, -4);
		$data = Util::converteData($data);
		
		$this->eventos = EventoTable::retornarEventos(5, array('dt_evento' => $data));
		
		$output = "";
		foreach($this->eventos as $evento)
		{
			$output = link_to(
				'<span class="b">'.$evento['dt_evento'].'</span> - ' . $evento['nm_evento'] . '<br /><br />',
				url_for('@evento?id_evento='.$evento['id_evento'])
			);	
		}
		
		return $this->renderText($output);
	}
	
	public function executeExtra(sfWebRequest $request)
	{
		try {
			$this->item = $this->getRoute()->getObject();
			
			addMeta($this->item->getDsResumoItem());
		$this->getResponse()->addMeta('description', $this->item->getDsResumoItem());	
			
		} catch(Exception $e){
			$this->getUser()->setFlash(
				'alert',
				'Não foi possível carregar o conteudo, por favor tente novamente.');
			$this->redirect('@homepage');
		}
	}
	
	public function executeAssinarNewsletter(sfWebRequest $request)
	{
		try {
			$formData = new FormData($this->getRequestParameter('mailing_list'));
			$formData->setCulture($this->getUser()->getCulture());
			
			// verifico se o email já está cadastrado
			$email = MailingListTable::verificarCadastrado($formData->get('ds_email_list'));
			if($email)
				throw new Exception('O email informado j&aacute; existe.');
				
			$mailinglist = new MailingList();
			$mailinglist->set('ds_nome_list', $formData->get('ds_nome_list'));
			$mailinglist->set('ds_email_list', $formData->get('ds_email_list'));
			$mailinglist->save();
			
			$result = array(
				'success' => utf8_encode('<font color="green">Cadastro realizado com sucesso!</font>')
			);
	
			$this->getResponse()->setHttpHeader('Content-type','application/json; charset=utf-8');
			return $this->renderText(json_encode($result));
		}
		catch(Exception $e)
		{
			$result = array(
				'success' => utf8_encode('<font color="red">'.$e->getMessage().'</font>')
			);
	
			$this->getResponse()->setHttpHeader('Content-type','application/json; charset=utf-8');
			return $this->renderText(json_encode($result));
		}
	}
}
